<template>
    <!-- 转正申请 -->
    <div>
        <el-row :gutter="24">
            <el-col :span="2">
                <div class="grid-content ep-bg-purple">
                    <el-button type="primary" plain @click="add" style="width: 100px;"><el-icon>
                            <Plus />
                        </el-icon>添加</el-button>
                </div>
            </el-col>
            <el-dialog title="添加转正申请" v-model="AddDisplay" fullscreen destroy-on-close>
              <OnboardingAddition @refresh="handleAddSuccess"></OnboardingAddition>
            </el-dialog>
            <el-col :span="1.5">
                <el-button type="primary" plain style="border: none;  ">
                    导入
                <i class="el-icon-upload el-icon--right"></i>
            </el-button>
            </el-col>

            <el-col :span="1.5">
                <el-button type="primary" plain style="border: none; ">
                    导出
                    <i class="el-icon-upload el-icon--right"></i>
                </el-button>
            </el-col>
             <el-col :span="2">
                <div class="grid-content ep-bg-purple">
                <el-button type="danger" plain @click="handleDelete">
                    <el-icon>
                    <Delete />
                    </el-icon>删除
                </el-button>
                </div>
            </el-col>
            <el-dialog v-model="deleteDialogVisible" title="确认删除" width="30%">
              <span>确定要删除选中的转正申请吗？</span>
              <template #footer>
                <span class="dialog-footer">
                  <el-button @click="deleteDialogVisible = false">取消</el-button>
                  <el-button type="danger" @click="confirmDelete">确认删除</el-button>
                </span>
              </template>
            </el-dialog>
            <el-col :span="2">
                <div class="grid-content ep-bg-purple">
                <el-button type="success" plain @click="approveSelected" style="width: 100px;">
                    <el-icon><Check /></el-icon>审核
                </el-button>
                </div>
            </el-col>
            <el-col :span="5">
                <div class="grid-content ep-bg-purple">
                </div>
            </el-col>

            <el-col :span="4">
                <div class="grid-content ep-bg-purple-light"> <el-input style="width: 180px" size="large"
                        placeholder="搜索">
                        <template #prefix><el-icon class="el-input__icon">
                                <search />
                            </el-icon></template></el-input>
                </div>
            </el-col>

            <el-col :span="1">
                <div class="grid-content ep-bg-purple-light">
                    <a-tooltip content="筛选" position="bottom" background-color="rgb(52, 145, 250)" mini>
                        <el-button size="default" @click="dialog = true"><el-icon>
                                <Filter />
                            </el-icon></el-button>
                    </a-tooltip>
                </div>
            </el-col>

            <el-col :span="1">
                <div class="grid-content ep-bg-purple-light"> <a-tooltip content="排序" position="bottom"
                        background-color="rgb(52, 145, 250)" mini>
                        <el-button size="default" @click=""><el-icon>
                                <Sort />
                            </el-icon></el-button>
                    </a-tooltip>
                </div>
            </el-col>


            <el-col :span="2">
                <div class="grid-content ep-bg-purple-light"><a-tooltip content="刷新" position="bottom"
                        background-color="rgb(52, 145, 250)" mini>
                        <el-button size="default" @click=""><el-icon>
                                <Refresh />
                            </el-icon></el-button>
                    </a-tooltip>
                </div>
            </el-col>
        </el-row>


            <el-table 
                ref="multipleTable"
                :data="data" 
                border 
                style="width: 100%;" 
                @cell-dblclick="handleClick"
                @selection-change="handleSelectionChange">
                
                <!-- 修改选择列 -->
                <el-table-column 
                type="selection" 
                label="选择" 
                fixed="left" 
                width="50" />
                <el-table-column 
                v-for="col in columns" 
                :prop="col.id" 
                :key="col.id" 
                :label="col.label" 
                :width="col.width">
                <template #default="scoped" :data="page.records ">
                  
                    <el-button 
                    v-if="col.id === 'Creator4' && scoped.row.Creator4 === '良好'"
                    :style="{ backgroundColor: '#00AED1', borderColor: '#00AED1', color: '#FFFFFF' }" 
                    disabled>
                    {{ scoped.row.Creator4 }}
                    </el-button>
                    <el-tag v-else-if="col.id === 'approvalStatus'" 
                        :type="scoped.row.approvalStatus === '已审核' ? 'success' : 'info'">
                        {{ scoped.row.approvalStatus || '未审核' }}
                      </el-tag>
                    <el-button 
                    v-if="col.id === 'Creator5' && scoped.row.Creator5 === '通过'"
                    :style="{ backgroundColor: '#43B96A', borderColor: '#43B96A', color: '#FFFFFF' }" 
                    disabled>
                    {{ scoped.row.Creator5 }}
                    </el-button>
                    <el-button 
                    v-if="col.id === 'Creator8' && scoped.row.Creator8 === '已确认'"
                    :style="{ backgroundColor: '#FC2A04', borderColor: '#FC2A04', color: '#FFFFFF' }" 
                    disabled>
                    {{ scoped.row.Creator8 }}
                    </el-button>
                    <el-button 
                    v-if="col.id === 'Creator8' && scoped.row.Creator8 === '已拒绝'"
                    :style="{ backgroundColor: '#B3C0D1', borderColor: '#304156', color: '#FFFFFF' }" 
                    disabled>
                    {{ scoped.row.Creator8 }}
                    </el-button>
                </template>
                </el-table-column>
            </el-table>
        <el-pagination v-model:current-page="page.current" v-model:page-size="page.size" :page-sizes="[1, 2, 3, 10]"
            :disabled="disabled" layout="total, sizes, prev, pager, next, jumper" :total="page.total" @current-change="handleCurrentChange">
        </el-pagination>

    </div>
    <!-- 详情页面 -->
        <el-dialog title="详细信息" v-model="isVisible" fullscreen destroy-on-close>
            <hr />
            <DetailsOfTheTalent 
                :regularization-id="selectedRegularizationId"
                @refresh="fetchRegularizationList">
            </DetailsOfTheTalent>
        </el-dialog>

    <!--筛选  -->
    <el-drawer v-model="dialog" title="筛选" direction="rtl" class="demo-drawer">
        <div class="demo-drawer__content">
            <el-form :model="form" style="height: 600px;">
                <el-select v-model="Screening" placeholder="筛选" style="width: 360px" placement="bottom">
                    <template #label="{ label, value }">
                        <span style="font-weight: bold">{{ label }}</span>
                    </template>
                    <el-option v-for="item in FilterData" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>

            </el-form>
            <div class="demo-drawer__footer">
                <el-button @click="cancelForm">取消</el-button>
                <el-button type="primary" :loading="loading" @click="onClick">
                    {{ loading ? '提交中 ...' : '提交' }}
                </el-button>
            </div>
        </div>
    </el-drawer>
    <el-dialog title="添加" v-model="AddDisplay" fullscreen destroy-on-close>
        <OnboardingAddition></OnboardingAddition>
    </el-dialog>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import request from '@/api/request'
import OnboardingAddition from '@/views/onboarding/turnPositive/insert.vue'
import DetailsOfTheTalent from '@/views/onboarding/turnPositive/detailed.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete } from '@element-plus/icons-vue'

const deleteDialogVisible = ref(false)
const selectedRows = ref([]) 

// 表格选择事件处理
const handleSelectionChange = (rows) => {
  selectedRows.value = Array.from(rows);
  console.log('选中行数据:', selectedRows.value);
}
//查询分页
const getPage = () => {
  request({
    url: 'into/findPage',
    method: 'get',
    params: {
      pageNum: page.value.current,
      pageSize: page.value.size
    }
  }).then(res => {
    console.log("后端返回原始数据:", res);
    if (res && res.data) {
      page.value = {
        current: res.data.current || page.value.current,
        size: res.data.size || page.value.size,
        total: res.data.total || 0,
        records: res.data.records || []
      };
      
      if (!Array.isArray(page.value.records)) {
        page.value.records = [];
      }
      
      applyLocalApprovalStatus();
    } else {
      page.value.records = [];
    }
    console.log("处理后的页面数据:", page.value);
  }).catch(err => {
    console.error("读取失败", err);
    page.value.records = [];
  })
}
const confirmDelete = async () => {
  try {
    // 显示加载状态
    deleteDialogVisible.value = false;
    ElMessage.info('正在删除，请稍候...');
    // 获取所有要删除的ID
    const validRows = selectedRows.value.filter(row => row.id || row.regularizationId);
    const ids = validRows.map(row => row.id || row.regularizationId);
    
    if (ids.length === 0) {
      ElMessage.error('没有有效的记录可以删除');
      return;
    }
    
    console.log('要删除的IDs:', ids);
    
    // 尝试批量删除接口
    const response = await axios.post('/api/regularization/batch-delete', { ids });
    
    if (response.data.code === 200) {
      ElMessage.success('删除成功');
      fetchRegularizationList();
    } else {
      ElMessage.error(response.data.message || 'HR已确认无法删除');
    }
  } catch (error) {
    console.error('删除失败:', error);
    
    if (error.response?.status === 500) {
      ElMessage.error('服务器内部错误');
    } 
    else if (error.response?.status === 404) {
      ElMessage.warning('批量删除功能暂不可用');
      await deleteOneByOne();
    } else {
      ElMessage.error('删除失败: ' + (error.response?.data?.message || error.message));
    }
  }
};

// 单个删除的备用方法
const deleteOneByOne = async () => {
  try {
    const validRows = selectedRows.value.filter(row => row.id || row.regularizationId);
    
    if (validRows.length === 0) {
      ElMessage.error('没有有效的记录可以删除');
      return;
    }
    
    // 逐个删除并收集结果
    const deleteResults = [];
    for (const row of validRows) {
      try {
        const id = row.id || row.regularizationId;
        console.log('正在删除ID:', id);
        const response = await axios.delete(`/api/regularization/${id}`);
        deleteResults.push({ id, success: response.data.code === 200, response });
      } catch (error) {
        deleteResults.push({ id: row.id || row.regularizationId, success: false, error });
        console.error(`删除ID ${row.id || row.regularizationId} 失败:`, error);
      }
    }
    
    // 统计结果
    const successCount = deleteResults.filter(r => r.success).length;
    const failCount = deleteResults.length - successCount;
    
    if (successCount > 0) {
      ElMessage.success(`成功删除 ${successCount} 条记录`);
      if (failCount > 0) {
        ElMessage.warning(`${failCount} 条记录删除失败`);
      }
      deleteDialogVisible.value = false;
      fetchRegularizationList();
    } else {
      ElMessage.error('所有记录删除失败');
    }
    
    // 输出详细日志
    console.log('删除结果详情:', deleteResults);
  } catch (error) {
    console.error('单个删除过程中出现异常:', error);
    ElMessage.error('删除过程中出现异常: ' + (error.message || '未知错误'));
  }
};

const handleDelete = () => {
  console.log('选中的行:', selectedRows.value);
  if (!selectedRows.value || selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要删除的记录');
    return;
  }
  
  // 检查选中行是否包含ID
  const validRows = selectedRows.value.filter(row => row.id || row.regularizationId);
  if (validRows.length === 0) {
    ElMessage.error('选中的记录缺少ID信息，无法删除');
    console.error('选中的记录:', selectedRows.value);
    return;
  }
  
  if (validRows.length < selectedRows.value.length) {
    ElMessage.warning(`有${selectedRows.value.length - validRows.length}条记录缺少ID信息，仅删除有效的记录`);
  }
  
  deleteDialogVisible.value = true;
};

const isVisible = ref(false) 
const loading = ref(false) 
const dialog = ref(false)
const currentPage4 = ref(1)
const pageSize4 = ref(10)
const disabled = ref(false)
const total = ref(0)
const data = ref([])

const columns = ref([
    { id: 'approvalStatus', label: '审核状态', width: '120' }, 
    { id: 'JobNature', label: '申请日期', width: '200' },
    { id: 'CandidateName', label: '工号', width: '200' },               
    { id: 'Gender', label: '姓名', width: '120' },
    { id: 'EthnicGroup', label: '部门', width: '200' },
    { id: 'Origin', label: '职位', width: '200' },
    { id: 'HouseholdRegistration', label: '聘用形式', width: '200' },
    { id: 'PoliticalAppearance', label: '身份证号', width: '200' },
    { id: 'CellPhone', label: '入职日期', width: '200' },
    { id: 'Mailbox', label: '拟转正日期', width: '200' },
    { id: 'DateOfBirth', label: '正式薪资', width: '200' },
    { id: 'Age', label: '试用期薪资', width: '200' },
    { id: 'School', label: '部门主管', width: '200' },
    { id: 'Specialized', label: '评价项', width: '200' },
    { id: 'GraduationTime', label: '考评分数', width: '200' },
    { id: 'Creator', label: '试用期工作成果描述', width: '200' },
    { id: 'Creator1', label: '试用期综合自我评价', width: '200' },
    { id: 'Creator2', label: '转正材料', width: '200' },
    { id: 'Creator3', label: '平均得分', width: '200' },
    { id: 'Creator4', label: '评价等级', width: '200' },
    { id: 'Creator5', label: '是否通过试用期', width: '200' },
    { id: 'Creator6', label: '正式转正日期', width: '200' },
    { id: 'Creator7', label: '提交人', width: '200' },
    { id: 'Creator8', label: 'HR确认', width: '200' },
])

const form = ref()
const Screening = ref('') 
const FilterData = ref([ 
    { value: '全部', label: '全部' },
    { value: 'HR已确认', label: 'HR已确认' },
    { value: 'HR未确认', label: 'HR未确认' },
])
const selectedRegularizationId = ref(null)

const handleClick = (row) => {
    console.log(row)
    selectedRegularizationId.value = row.id || row.regularizationId || null
    isVisible.value = true
}
const AddDisplay = ref(false)

// 新增功能
const add = () => {
  selectedRegularizationId.value = null 
  AddDisplay.value = true
}
const handleAddSuccess = () => {
  AddDisplay.value = false
  fetchRegularizationList()
}
const approveSelected = () => {
  if (!selectedRows.value || selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要审核的数据')
    return
  }
  
  // 更新选中行的审核状态
  selectedRows.value.forEach(row => {
    row.approvalStatus = '已审核'
  })
  
  ElMessage.success(`成功审核 ${selectedRows.value.length} 条数据`)
  
  // 保存审核状态到本地存储
  saveApprovalStatus(selectedRows.value);
  
  // 更新页面数据以反映审核状态
  updatePageData(selectedRows.value);
}

const applyLocalApprovalStatus = () => {
  if (!data.value || !Array.isArray(data.value)) {
    return;
  }
  
  const approvalStatus = loadApprovalStatus();
  
  if (Object.keys(approvalStatus).length > 0) {
    const updatedRecords = [...data.value];
    
    updatedRecords.forEach(record => {
      const id = record.id;
      if (id && approvalStatus[id]) {
        record.approvalStatus = approvalStatus[id];
      }
    });
    
    data.value = updatedRecords;
  }
}
// 从本地存储加载审核状态
const loadApprovalStatus = () => {
  try {
    const approvalStatus = JSON.parse(localStorage.getItem('employeeApprovalStatus') || '{}');
    return approvalStatus;
  } catch (error) {
    console.error('加载审核状态失败:', error);
    return {};
  }
}
const updatePageData = (updatedRows) => {
  const updatedRecords = [...data.value];
  
  updatedRows.forEach(updatedRow => {
    const index = updatedRecords.findIndex(record => 
      (record.id) === (updatedRow.id)
    );
    
    if (index !== -1) {
      updatedRecords[index] = { ...updatedRecords[index], approvalStatus: '已审核' };
    }
  });
  
  // 更新页面数据
  data.value = updatedRecords;
}
const saveApprovalStatus = (approvedRows) => {
  try {
    // 获取现有的审核状态
    const existingStatus = JSON.parse(localStorage.getItem('employeeApprovalStatus') || '{}');
    
    // 更新审核状态
    approvedRows.forEach(row => {
      const id = row.employeeId || row.id;
      if (id) {
        existingStatus[id] = '已审核';
      }
    });
    
    // 保存到本地存储
    localStorage.setItem('employeeApprovalStatus', JSON.stringify(existingStatus));
  } catch (error) {
    console.error('保存审核状态失败:', error);
  }
}
// 获取转正申请列表数据
onMounted(() => {
  fetchRegularizationList().then(() => {
    console.log('数据加载完成，检查数据结构:', data.value);
  });
});
const multipleTable = ref()
const fetchRegularizationList = async () => {
  try {
    const response = await axios.get('/api/regularization/list', {
      params: {
        pageNum: currentPage4.value,
        pageSize: pageSize4.value
      }
    })
    
    if (response.data.code === 200) {
      data.value = response.data.data.records.map(item => ({
        id: item.id || item.regularizationId, 
        JobNature: item.applicationTime ? formatDate(item.applicationTime) : '',
        CandidateName: item.workNumber,
        Gender: item.regularizationName,
        EthnicGroup: item.department,
        Origin: item.posts,
        HouseholdRegistration: item.employmentForm,
        PoliticalAppearance: item.identityCard,
        CellPhone: item.onboarding ? formatDate(item.onboarding) : '',
        Mailbox: item.turnPositive ? formatDate(item.turnPositive) : '',
        DateOfBirth: item.salary,
        Age: item.probationarySalary,
        Creator: item.description,
        Creator1: item.selfEvaluation,
        Creator3: item.averageScore,
        Creator4: item.evaluationLevel,
        Creator5: item.supervisor === '通过' ? '通过' : '未通过',
        Creator6: item.officialDate ? formatDate(item.officialDate) : '',
        Creator8: item.hrConfirm
      }))
      
      console.log('处理后的数据:', data.value);
      total.value = response.data.data.total
    }
  } catch (error) {
    console.error('获取转正申请列表失败:', error)
  }
}

// 格式化日期函数
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}


const onClick = () => {
    loading.value = true
    setTimeout(() => {
        loading.value = false
        dialog.value = false
    }, 400)
}

const cancelForm = () => {
    loading.value = false
    dialog.value = false
}

// 分页变化处理
const handleCurrentChange = (val) => {
  currentPage4.value = val
  fetchRegularizationList()
}

const handleSizeChange = (val) => {
  pageSize4.value = val
  currentPage4.value = 1
  fetchRegularizationList()
}
//查询分页
const page = ref({
    current: 1,
    size: 4,
    total: 10,
    records: []
})

// 组件挂载时获取数据
onMounted(() => {
  fetchRegularizationList()
})
</script>

<style scoped></style>
